<template>
    <div class="content pl-[15px] pr-[15px]">
      <el-tabs v-model="active" @tab-change="handleTabClick">
        <el-tab-pane label="录播使用详情" name="1">
          <el-row class="tips p-[10px] mb-[15px]">录播数据概况（数据T+1更新 | 当日4:00更新前一天数据）</el-row>
          <el-button class="mb-[15px]" type="primary" @click="broadcast">录播充值</el-button>
          <el-row v-if="detail" class="mb-[15px]" :gutter="10">
              <el-col :span="8">
                  <el-card class="text-center" shadow="hover">
                      <div class="text-[30px] font-bold">{{ Number(detail[1].count - detail[1].usage).toFixed(2) }}</div>
                      <div class="text-[#999]">可用流量（TB）</div>
                  </el-card>
              </el-col>
              <el-col :span="8">
                  <el-card class="text-center" shadow="hover">
                      <div class="text-[30px] font-bold">{{ Number(detail[1].count).toFixed(2) }}</div>
                      <div class="text-[#999]">总充值流量（TB）</div>
                  </el-card>
              </el-col>
              <el-col :span="8">
                  <el-card class="text-center" shadow="hover">
                      <div class="text-[30px] font-bold">{{ Number(detail[1].usage).toFixed(2) }}</div>
                      <div class="text-[#999]">已消耗流量（TB）</div>
                  </el-card>
              </el-col>
          </el-row>
          <f-table ref="tableRef1" @register="registerTable1">
          </f-table>
        </el-tab-pane>
        <el-tab-pane label="直播使用详情" name="2">
          <el-row class="tips p-[10px] mb-[15px]">直播数据概况（数据T+1更新 | 当日4:00更新前一天数据）</el-row>
          <el-button class="mb-[15px]" @click="broadcast" type="primary">直播充值</el-button>
          <el-row v-if="detail" class="mb-[15px]" :gutter="10">
              <el-col :span="8">
                  <el-card class="text-center" shadow="hover">
                      <div class="text-[30px] font-bold">{{ Number(detail[2].count - detail[2].usage).toFixed(2) }}</div>
                      <div class="text-[#999]">可用流量（TB）</div>
                  </el-card>
              </el-col>
              <el-col :span="8">
                  <el-card class="text-center" shadow="hover">
                      <div class="text-[30px] font-bold">{{ Number(detail[2].count).toFixed(2) }}</div>
                      <div class="text-[#999]">总充值流量（TB）</div>
                  </el-card>
              </el-col>
              <el-col :span="8">
                  <el-card class="text-center" shadow="hover">
                      <div class="text-[30px] font-bold">{{ Number(detail[2].usage).toFixed(2) }}</div>
                      <div class="text-[#999]">已消耗流量（TB）</div>
                  </el-card>
              </el-col>
          </el-row>
          <f-table ref="tableRef2" @register="registerTable2" v-if="active == '2'">
          </f-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 新建分组弹框 -->
    <el-dialog :title="active == '1' ? '录播充值' : '直播充值'" v-model="dialogFormVisible" width="500px">
        <el-form :model="form" :rules="rules" ref="formRef">
            <el-form-item label="充值流量数" label-width="100" prop="value">
                <el-input v-model.trim="form.value" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="充值密码" label-width="100" prop="password">
                <el-input type="password" v-model.trim="form.password" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirm">确 定</el-button>
        </div>
    </el-dialog>
  </template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { t } from '@/lang'
import FTable, { BasicColumn, useTable } from '@/addon/htscrm/components/f-table'
import { tableColumns, tableColumns2 } from '@/addon/htscrm/data/store.cdp'
import { getStoreMoneyLogApi, getCdnDataApi, getCdnUseLogApi, addCdnDataApi } from '@/addon/htscrm/api'
import { ElMessage, FormRules, FormInstance } from "element-plus";

const detail = ref<any>()
const active = ref('1')

const tableRef1 = ref()
const { methods: table1Methods, register: registerTable1 } = useTable({
    rowKey: 'id',
    hideTableHeader: true,
    columns: tableColumns(t) as BasicColumn<any>[],
    beforeFetch: (opt) => {
        return {
            ...opt,
            product: 1,
        };
    },
    api: async (opt) => (await getCdnUseLogApi(opt)).data
})

const { methods: table2Methods, register: registerTable2 } = useTable({
    rowKey: 'id',
    hideTableHeader: true,
    columns: tableColumns(t) as BasicColumn<any>[],
    beforeFetch: (opt) => {
        return {
            ...opt,
            product: 2,
        };
    },
    api: async (opt) => (await getCdnUseLogApi(opt)).data
})

// 表单规则
const rules = reactive<FormRules>({
  value: [
        { required: true, message: "请输入充值数量", trigger: "blur" },
        {
            validator: (rule, value, callback) => {
                // 检查是否可以转换为有效数字
                if (value === '' || isNaN(Number(value)) || !Number.isFinite(Number(value))) {
                    callback(new Error('充值数量必须为有效数字值'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const handleTabClick = (tab: string) => {
    console.log(active.value,tab);
    // active.value = tab
    if (tab == '1') {
        table1Methods.reload()
    } else {
        table2Methods.reload()
    }
}


const dataDisplay = async () => {
    const { data } = await getCdnDataApi({})
    
    detail.value = data
}

const dialogFormVisible = ref(false);
const form = ref({
    product: 1,
    value: "",
    password: "",
});
const broadcast = async () => {
    form.value.value = ""
    form.value.password = ""
    dialogFormVisible.value = true;
}

const formRef = ref<FormInstance>()
const confirm = async () => {
    const formEl = formRef.value
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (!valid) return
        form.value.product = Number(active.value)
        const res = await addCdnDataApi(form.value)
        
        if (res.code == 1) {
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            if (active.value == '1') {
                table1Methods.reload()
            } else {
                table2Methods.reload()
            }
            await dataDisplay()
            dialogFormVisible.value = false
            
        } else {
            ElMessage({
                message: res.msg,
                type: 'error',
            })
        }
    })
}

onMounted(async () => {
    await dataDisplay()
})

</script>

  <style lang="scss" scoped>
  .content {
    background-color: var(--el-bg-color);

    .tips {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
        font-size: 14px;
    }
  }
  </style>
